<template>
    <div style="padding-bottom: 80px">
        <div class="location">
            <div class="addressInfo" @click="$router.push('/address/list?type=select')" v-if="addressInfo.addrId">
                <p class="name">{{addressInfo.deliName}}&nbsp;&nbsp;{{addressInfo.tel}}</p>
                <div class="address"><span class="tag tag_red" v-if="addressInfo.defaultTag == 1">默认</span>{{addressInfo.provinceName}}{{addressInfo.cityName}}{{addressInfo.districtName}}&nbsp;{{addressInfo.address}}</div>
            </div>
            <!-- <div v-else style="flex: 1" @click="$router.push('/address/add?type=select')"> -->
            <div v-else style="flex: 1" @click="$router.push('/address/list?type=select')">
                <!-- <van-icon name="add-square"></van-icon> -->
                <span class="emptyAddress">添加收货地址</span>
            </div>
            <van-icon name="arrow" color="#999"></van-icon>
        </div>


        <ul class="storeList">
            <li v-for="shop in orderList" :key="shop.shopName">
                <div class="storeInfo">
                    <i class="van-icon van-icon-shop-o"></i>
                    <em>{{shop.shopName}}</em>
                </div>
                <ul class="goodsList">
                    <li class="item"  v-for="goods in shop.shopOrderItemsList" :key="goods.orderItemId"> 
                        <img :src="'/images' + goods.titleImage"  class="img">
                        <div class="content">
                            <div class="name">{{goods.title}}</div>
                            <div class="sku">{{goods.goodsSpecName}}</div>
                            <div class="other">
                                <div class="price">¥<em>{{goods.unitPrice | money}}</em></div>
                                <span>数量:&nbsp;{{goods.productNum}}</span>
                            </div>
                        </div>
                    </li>
                </ul>
                <div class="tips vux-1px-t">
                    运费:&nbsp;<span>¥<em>{{shop.shopOrder.freightAmount | money}}</em></span>
                    商品总计:&nbsp;<span>¥<em>{{shop.shopOrder.productAmount | money}}</em></span>
                </div>
            </li>
        </ul>
        <van-field
            style="margin-top: 10px;"
            v-model="message"
            label="留言"
            type="textarea"
            placeholder="请输入留言"
            rows="1"
            @input="errorMsg = ''"
            :error-message="errorMsg"
            autosize
        />
        <!-- 支付方式在进入订单支付页面时会返回建行随付贷或者其他（微信/支付宝等），前展示为选择期数，后展示如下 -->
        <van-cell :title="payWayItem.payWayText" :value="payWayItem.text" is-link @click="popShow = true;"></van-cell>

        <van-field
            clearable
            label="营销代码"
            placeholder="营销人员代码（选填）"
            input-align="right"
            bind:click-icon="onClickIcon"
            v-model="recommandMarketCode"
            type="number"
        />

        <van-cell title="优惠券" is-link @click="discountCardShow = true"></van-cell>
        
        <!-- <van-submit-bar
            :price="productAmount"
            button-text="去支付"
            :loading="loading"
            @submit="onSubmit"
            >
        </van-submit-bar> -->
        <!-- :tip="productNumbers" -->
        <div class="fixedBotoomPayMask">
            <div class="fixedBotoomPay">
                <div class="fixedBotoomPayLeft"><i>合计：</i>{{productNumbers}}</div>
                <div class="fixedBotoomPayRight" @click="onSubmit()">去支付</div>
            </div>
        </div>

        <!-- 其他支付方式选择 -->
        <van-popup position="bottom" v-model="popShow">
            <van-picker :columns="payType"  show-toolbar @cancel="popShow = false" @confirm="areaChange"></van-picker>
        </van-popup>

        <!-- 支付输入密码弹出框+密码键盘 -->
        <select-pay-type :show.sync="showPop" :order="$route.query.order" :payId="payId" :money="productAmount" :payWayItem="payWayItem" @paySuccess="paySuccess"></select-pay-type>
    </div>
</template>
<script>
import selectPayType from './../../components/selectPayType';
export default {
    name: 'payOrder',
    data() {
        return {
            showPop: false, //显示输入密码
            message: '',
            addressInfo: {},
            productAmount: 0,
            productNumbers: '', // 分期数
            orderList: {},
            goodsCount: 0, //商品数量
            loading: false, 
            payId: '',
            errorMsg: '',
            payWayItem: {}, //选中的支付方式
            payWayItem1: {}, //随付贷选中的分期期数
            money: 0, //总价
            payType: [], //支付方式
            payTypeValue:'', // wechart pay 支付参数--payType
            popShow: false, //切换支付方式
            popShowNum: false, // 切换随付贷期数
            payWay: 1, // 支付方式，10-随付贷   1-其它
            recommandMarketCode: '',
            discountCardShow: false, // 选择优惠券弹窗
        }
    },

    methods: {
        onSubmit() {
            if (!this.addressInfo.addrId) {
                this.$toast(`请选择收货地址`);
                return;
            }
            if (this.message.length > 250) {
                this.errorMsg = '留言不能超过250个字符';
                return;
            }

            // 根据this.payTypeData来判断支付类型 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // if ( this.payWayItem.picklistId === 13) {
            //     this.$toast(`暂不支持${this.payWayItem.picklistText}`);
            //     return;
            // }
            
            let orders = this.orderList.map(e => e.shopOrder.orderSn);
            var requeseDataForConfirm = {
                token: localStorage.getItem('token'),
                orderIds: `|${orders.join('||')}|`,
                addrId: this.addressInfo.addrId,
                userRemak: this.message,
            }
            if (this.recommandMarketCode!='') {
                requeseDataForConfirm.recommandMarketCode = this.recommandMarketCode
            }
            this.$http.post('/shop/order/front/confirmOrders', requeseDataForConfirm).then(res => {
                if (res.status === 0) {
                    console.log('确认订单（保存收货地址+用户留言）')
                    console.log(res)
                    this.payId = res.data;
                    // if (this.payWayItem.picklistId == 12) {
                        this.wechatPay();
                        // return;
                    // }
                    // 支付密码弹窗
                    // this.showPop = true;
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        wechatPay() {
            // 支付方式确认为随付贷/其他方式支付
            // 根据payWayItem1.picklistId返回判断随付贷选择分期期数
            // 根据payWayItem.picklistId返回判断其他支付方式
            console.log(this.payType)
            let requeseDataForPay = {
                token: localStorage.getItem('token'),
                payId: this.payId,
                payMethod: this.payWay,
                payType: this.payTypeValue,
                openId: this.$store.state.userInfo.openId
            }
            if (this.payWay == 1) {
                console.log('去支付--其他支付')
            } else if (this.payWay == 10) {
                console.log('去支付--分期支付')
                requeseDataForPay.stageNumId = this.payType.stageNumId
                requeseDataForPay.stageNum = this.payType.stageNum
            }

            this.$http.post('/shop/orderPay/front/doOrderPay', requeseDataForPay).then(res => {
                console.log('res is');
                console.log(res);
                if (res.status === 0) {
                    /**
                     * 测试龙支付
                     */
                    var jsonData = JSON.parse(res.data);
                    console.log('jsonData.result is');
                    console.log(jsonData.result);
                    // this.$route.push(jsonData.result);
                    //  window.location="mbspay://direct?" + jsonData.payinfo;
                    // window.location.href = jsonData.result;
                    this.useWxPay(JSON.parse(res.data));
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        useWxPay(data) {
            let self = this;
            function onBridgeReady(){
                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', Object.assign({"appId":"wx0f1080bae2ad5ced",}, data),
                    function(res){
                        if(res.err_msg == "get_brand_wcpay_request:ok" ){
                            self.$toast.success('支付成功');
                            self.paySuccess();
                        } 
                    }
                ); 
            }
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            }else{
                onBridgeReady();
            }
        },

        paySuccess() {
            setTimeout(() => {
                let order = decodeURI(this.$route.query.order);
                order = order.replace(/\|/g, '');
                this.$router.replace('/order/list');
            }, 700)
        },
        
        getOrder() {
            this.$http.post('/shop/order/front/getToConfirmOrderList', {
                orderIds: decodeURI(this.$route.query.order),
                token: localStorage.getItem('token')
            }).then(res => {
                console.log('查询待确定订单信息成功')
                console.log(res)
                if (res.status === 0) {
                    if (localStorage.getItem('selectAddrId')) {
                        this.getAddrById(localStorage.getItem('selectAddrId'));
                        localStorage.removeItem('selectAddrId');
                    } else if (res.data.defaultDeliAddr){
                        this.addressInfo = res.data.defaultDeliAddr;
                    }
                    let productAmount = 0;                     
                    this.orderList = res.data.shopOrderList.map(e => {
                        productAmount += e.shopOrder.productAmount;
                        productAmount += e.shopOrder.freightAmount;                        
                        return e;
                    });
                    this.productAmount = productAmount;                    
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        areaChange(item) {
            console.log(item)
            console.log('当前支付方式：'+this.payWay)
            this.payWayItem = item;
            this.popShow = false;
            let productNumbers = ''; // 分期数
            if (this.payWay == 1) {
                this.payTypeValue = item.payType
                productNumbers = '￥'+ (this.money/100).toFixed(2) // 设置分期数
                this.productNumbers = productNumbers;
            } else if (this.payWay == 10) {
                this.payTypeValue = this.payTypeList[0].payType                
                productNumbers = '￥'+ (this.money/100/this.payWayItem.stageNum).toFixed(2) +' * ' +this.payWayItem.stageNum+ '期' // 设置分期数
                this.productNumbers = productNumbers;
            }
            console.log(this.payTypeValue)        
            if (item.picklistId === 13) {
                this.$toast(`暂不支持${this.payWayItem.picklistText}`);
                this.popShow = false;
            }
        },        

        getPayTypeList() { // 其他支付方式
            this.$http.post('/shop/orderPay/front/getToOrderPay', {
                orderIds: this.$route.query.order,
                token: localStorage.getItem('token')
            }).then(res => {
                console.log('获取支付前数据成功')
                console.log(res)
                // 通过res.data.payMethod返回的payMethod（1/10）判断商铺当前支付方式
                // if payMethod == 1 -> 看payTypeList得出支付方式列表
                // if payMethod == 10 -> 看stageNumList得出支付方式列表
                // 订单支付接口所传参数payType=payTypeList[0].payType【如果支付方式=10，此数组只返回一组数据，=1则传相应值】
                if (res.status === 0) {
                    this.money = res.data.productAmount;
                    this.payWay = res.data.payMethod.payMethod // 1-其他支付方式 10-随付贷                    
                    let productNumbers = ''; // 支付方式为其它时代表总价，为随付贷支付时代表分期总价，在顶部总计菜单栏显示
                    
                    if (this.payWay == 1) {
                        productNumbers = '￥'+ (this.money/100).toFixed(2) // 总价
                        this.productNumbers = productNumbers;

                        this.payType = res.data.payTypeList.map(e => {
                            e.text = e.payTypeName;
                            e.value = e.payTypeName;
                            e.payWayText = '支付方式'
                            return e;
                        });                        
                    } else if (this.payWay == 10) {
                        this.stageNum = res.data.stageNumList[0].stageNum // 首选数组下标为0的stageNum
                        
                        productNumbers = '￥'+ (this.money/100/this.stageNum).toFixed(2) +' * ' +this.stageNum+ '期' // 分期总价
                        this.productNumbers = productNumbers;

                        this.payType = res.data.stageNumList.map(e => {
                            e.text = e.stageNumName+'期';
                            e.value = e.stageNum;
                            e.payWayText = '分期期数'
                            return e;
                        });                        
                    }
                    console.log('获取this.payType')
                    console.log(this.payType)
                    this.payTypeList = res.data.payTypeList
                    if (res.data.payTypeList.length > 0) {
                        this.payWayItem = this.payType[0]; // 支付方式 _ 默认展示项
                        this.payTypeValue = this.payType[0].payType
                    }
                }
            })
        },

        getDefaultAddr() {
            this.$http.post('/shop/userDeliAddr/front/getDefaultDeliAddr').then(res => {
                if (res.status === 0) {
                    this.addressInfo = res.data; 
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        getAddrById(id) {
            this.$http.post('/shop/userDeliAddr/front/getDeliAddr', {
                addrId: id
            }).then(res => {
                if (res.status === 0) {
                    this.addressInfo = res.data;
                    /**
                     *  addrId: 10
                        address: "123"
                        cityId: "110100"
                        cityName: "北京市"
                        createTime: "2019-03-12 00:01:14"
                        defaultTag: 0
                        deliName: "1"
                        districtId: "110101"
                        districtName: "东城区"
                        provinceId: "110000"
                        provinceName: "北京市"
                        tel: "13548948212"
                        userId: 1790
                        userName: "8613548948212"
                     */
                } else {
                    this.$toast.fail(res.message);
                }
            })
        }
    },

    components: { selectPayType },

    created() {
        this.getPayTypeList();
        this.getOrder();
    },
}
</script>

<style scoped lang="scss">
.location {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    padding: 15px;
    line-height: 21px;
    padding-bottom: 16px;
    background: #fff url() -7px bottom repeat-x;
    background-size: 64px 5px;
    /deep/ .van-icon-add-square {
        font-size: 40px;
        color: #38f;
        vertical-align: middle;
    }
    .emptyAddress {
        line-height: 40px;
        // margin-left: 10px;
        display: inline-block;
        vertical-align: middle;
        flex: 1;
    }
    .addressInfo {
        flex: 1;
        .name {
            word-wrap: break-word;
            word-break: break-all;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 5px;
        }   

        .address {
            word-wrap: break-word;
            word-break: break-all;
            color: #7d7e80;
            span {
                display: inline-block;
                position: relative;
                overflow: hidden;
                padding: 0 5px;
                vertical-align: middle;
                margin: -2px 5px 0 0;
                max-width: 8em;
                height: 15px;
                line-height: 15px;
                font-size: 10px;
                color: #e93b3d;
                &::after {
                    content: "";
                    position: absolute;
                    z-index: 1;
                    pointer-events: none;
                    background-color: #e93b3d;
                    border: 1px solid #ddd;
                    top: 0;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background: none;
                    border-color: #e93b3d;
                    border-radius: 2px;
                    right: -100%;
                    bottom: -100%;
                    -webkit-transform: scale(.5);
                    -webkit-transform-origin: 0 0;
                    border-radius: 4px;
                }
            }
        }
    }
}
.storeList {
    > li {background-color: #fff; margin-top: 10px; box-shadow: 0 0 5px 0 rgba(0,0,0,.1)}
    .storeInfo {
        display: flex;
        align-items: center;
        padding: 10px 12px;
        i {
            font-size: 16px;
            margin: 0 5px 0 8px;
        }

        em {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            flex: 1;
            box-sizing: border-box;
            display: inline-block;
            font-size: 16px;
            font-weight: 700;
            margin-right: 10px;
            width: 100%;
        }
    }   

    .tips {
        font-size: 12px;
        line-height: 40px;
        text-align: right;
        padding: 0 5px;
        border-color: #ccc;
        span {
            color: #ff6700;
            margin-right: 5px;
        }
    }
    
    .goodsList {
        .item {
            position: relative;
            overflow: hidden;
            background: #fff;
            z-index: 1;
            position: relative;
            min-height: 75px;
            padding: 5px 10px 15px 108px;
            background: #fff;
            -webkit-overflow-scrolling: touch;

            .select {
                z-index: 1;
                display: block;
                position: absolute;
                top: 0;
                left: 0;
                width: 63px;
                height: 100%;
                padding-top: 30px;
                padding-left: 12px
            }

            .img {
                position: absolute;
                left: 23px;
                top: 5px;
                display: block;
                width: 75px;
                height: 75px;
            }

            .content {
                min-height: 75px;
                .name {
                    font-size: 14px;
                    margin-bottom: 5px;
                    word-break: break-all;
                        overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                }
                .sku {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    position: relative;
                    background-color: #fff;
                    padding: 0;
                    border: none;
                    margin: 0;
                    font-size: 12px;
                    color: #999;
                    border-radius: 2px;
                }

                .other {
                    position: relative;
                    display: -webkit-box;
                    display: -webkit-flex;
                    display: flex;
                    -webkit-box-align: center;
                    -webkit-align-items: center;
                    align-items: center;
                    margin: 5px 0 0;
                    -webkit-box-pack: justify;
                    -webkit-justify-content: space-between;
                    justify-content: space-between;
                    .price {
                        flex: 1;
                        line-height: 16px;
                        color: #ff6700;
                        font-size: 10px;
                        em {
                            font-size: 16px;
                        }
                    }

                    span {
                        color: #999;
                    }
                }
            }
        }
    }
}
.van-submit-bar__tip{
    padding: 12px;
    font-size: 14px;
    line-height: 20px;
    text-align: right;
}
.van-submit-bar__price{
    color: #ff6700;
}
.van-submit-bar .van-button{
    background: #ff6700;
    border-radius: 0;
    border: 1px solid #ff7600;
}

.fixedBotoomPay{
    position: fixed;
    bottom: 0px;
    left: 0px;
    z-index: 999;
    display: flex;
    height: 44px;
    line-height: 44px;
    background: #fff;
    width: 100%;
    justify-content: center;
    align-items: center;
    flex-direction: row;
}
.fixedBotoomPayLeft{
    flex: 1.5;
    text-align: right;
    padding: 0 15px 0 0;
    color: #fe4646;
    font-weight: bold;
    font-size: 14px;
}
.fixedBotoomPayLeft i{color: #333333; font-style: normal;}
.fixedBotoomPayRight{
    flex: 1;
    text-align: center;
    background: #ff7600;
    color: #fff;
    font-size: 16px;
}

</style>
